﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace TicTacToe.WinForms
{
    public partial class BoardControl : UserControl
    {
        public event EventHandler<CellClickedEventArgs> CellClicked;

        public BoardControl()
        {
            InitializeComponent();

            button1.Tag = new Point(0, 0);
            button2.Tag = new Point(0, 1);
            button3.Tag = new Point(0, 2);

            button4.Tag = new Point(1, 0);
            button5.Tag = new Point(1, 1);
            button6.Tag = new Point(1, 2);

            button7.Tag = new Point(2, 0);
            button8.Tag = new Point(2, 1);
            button9.Tag = new Point(2, 2);
        }

        private void OnCellClicked(object sender, EventArgs e)
        {
            var button = sender as Button;

            if (button == null)
                throw new ArgumentException("The OnCellClicked event should only be triggered by a button");

            if (!(button.Tag is Point))
                throw new InvalidOperationException("A button triggering the OnCellClicked event must be tagged with a Location value reprenting its co-ordinates");
            
            CellClicked(sender, new CellClickedEventArgs((Point)button.Tag));
        }

        public void Reset()
        {
            //We know that the only buttons on this control are the cell buttons, so reset them all.
            foreach (var control in Controls.OfType<Button>())
            {
                control.Text = "";
                control.Enabled = true;
            }
        }

        public void SetCellContents(Point coOrdinates, Symbol symbol)
        {
            foreach (var control in Controls.OfType<Button>())
            {
                if ((Point)control.Tag == coOrdinates)
                {
                    control.Text = symbol == Symbol.Nought ? "O" : "X";
                    control.Enabled = false;
                }
            }
        }
    }
}
